<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
	<html lang="CN">
	<head>
		<title>有点功夫-有点功夫管理-地理分配</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="renderer" content="webkit">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		
		 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ho7fOFyxd0RsZdVt4Bqyy2Fh08CrukqY"></script>
		<jsp:include page="../../fragment/frag_top_css.jsp"/>
	  
	  	<jsp:include page="../../fragment/frag_top_js.jsp"/>
	  	
	   <style type="text/css">
       		#allmap {width: 100%;height: 100%;overflow: hidden;}
   	   </style>
   </head>
<body>
    <div class="site-holder">
      <!-- nav -->
	  <jsp:include page="../../fragment/frag_nav.jsp" />
     
          <!-- .box-holder -->
          <div class="box-holder">
		  <!--left-sidebar  -->
		  <jsp:include page="../../fragment/frag_left.jsp" />

            <!-- .content -->
            <div class="content">

                <div class="row">
                 <div class="col-mod-12">
                  <ul class="breadcrumb">
                   <li><span>有点功夫管理</span></li>
                   <li><a href="javascript:void(0)" class="active">地理分配</a></li>
                 </ul>
                 
                 <div class="form-group hiddn-minibar pull-right">
                  	<div id="toolbar" class="btn-group">
                  		<!-- 摆放按钮 -->
                  		<c:forEach var="g" items="${btns }">
                  			 <button type="button" class="btn btn-primary" onclick="${g.action }">
						 		<i class="${g.btnicon }"></i> ${g.btnname }
							 </button>
                  		</c:forEach>
 					 </div>
                </div>

                <h3 class="page-header"> 地理分配 <i class="fa fa-info-circle animated bounceInDown show-info"></i> </h3>

                <blockquote class="page-information hidden">
                 <p>
                  	更新、维护地理信息！
                </p>
              </blockquote>
            </div>
          </div>
				<div>
					<div class="row">
						<div class="col-md-12" style="height:80%">
							<div class="panel panel-cascade">
								<div class="panel-heading">
									<h3 class="panel-title text-primary">
										活动/场馆地理分配<span class="pull-right"> <a href="#"
											class="panel-minimize"><i class="fa fa-chevron-up"></i></a> <a
											href="#" class="panel-close"><i class="fa fa-times"></i></a>
										</span>
									</h3>
									
								</div>
									<div class="form-group" id="r-result">
										<input class="form-control" type="text" id="suggestId" size="50" placeholder="请输入详细地址快速定位" style="width:350px;" />
									</div>
									<div id="searchResultPanel"
										style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;">
									</div>
									<div class="panel-body nopadding">
										<div id="vmap">
											<div id="container"
												style="margin: 0 auto;height: 400px;width: 100%">
												<div id="allmap"></div>
											</div>
										</div>
									</div>
								<!-- /panel body -->
							</div>
						</div>
					</div>
				</div>
			</div>
	 </div>
	 <jsp:include page="../../fragment/frag_bottom_js.jsp"/>
</body>
</html>
<script type="text/javascript">

	var myIcon = new BMap.Icon("http://developer.baidu.com/map/jsdemo/img/fox.gif", new BMap.Size(300,157));

	var map = new BMap.Map("allmap");
	var point = new BMap.Point(121.481,31.221);
	var lng = "";
	var lat = "";
	var obj = null;
	//地图属性
	map.centerAndZoom(point, 14);
	map.enableScrollWheelZoom();
	map.enableInertialDragging();
	map.enableContinuousZoom();
	//城市搜索功能
	/* var size = new BMap.Size(10, 20);
	map.addControl(new BMap.CityListControl({
		anchor : BMAP_ANCHOR_TOP_LEFT,
		offset : size,
	})); */
	//菜单
	var menu = new BMap.ContextMenu();
	var txtMenuItem = [ {
		text : '<button class="btn btn-primary btn-xs"  style="width:100%" >添加活动</button>',
		callback : function() {
			addMap("${pageContext.request.contextPath}/baiduMapController/initDataForPro","11","活动信息填写");
		}
	}, {
		text : '<button class="btn btn-primary btn-xs"  style="width:100%" >添加场馆</button>',
		callback : function() {
			addMap("${pageContext.request.contextPath}/baiduMapController/initDataFoGym","12","场馆信息填写");
		}
	} ];
	for (var i = 0; i < txtMenuItem.length; i++) {
		menu.addItem(new BMap.MenuItem(txtMenuItem[i].text,
				txtMenuItem[i].callback, 100));
	}

	map.addContextMenu(menu);
	
	//锚点注册监听
	var removeMarker = function(e,ee,marker){
		
		//alert(JSON.stringify(this.obj))
		$.ajax({
		url : "${pageContext.request.contextPath}/baiduMapController/delMap",
		data : this.obj,
		type : "POST",
		async : true,
		dataType : "json",
		success : function(flag) {
			if(flag){
				map.removeOverlay(marker);
			}
			return ;
		},
		error : function() {
			bootbox.alert({ 
				  size: "small",
				  title: "错误",
				  message: "请求超时，请重试！", 
				  callback: function(){return; }
			});
			return;
		}
		});
		
	};
	
	// 编写自定义函数,创建标注
	function addMarker(point,ele){
		  
		var idx  = 0;
		if(ele.actType == "12"){
			idx = 1;
		}
		var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {  
              offset: new BMap.Size(10, 25), // 指定定位位置  
              imageOffset: new BMap.Size(0, 0 - idx * 25) // 设置图片偏移  
        });  
	 	var marker = new BMap.Marker(point,{icon:myIcon});
	 	//var marker = new BMap.Marker(point);
		//锚点右键菜单
		var markerMenu = new BMap.ContextMenu();
		markerMenu.addItem(new BMap.MenuItem('<button class="btn btn-primary btn-xs"  style="width:100%" >删除</button>',removeMarker.bind(marker)));
		marker.addContextMenu(markerMenu);
		
		map.addOverlay(marker);
		addRightClickHandler(ele,marker);
		addClickHandler(ele,marker);
	}
	
	//初始化锚点
	$.ajax({
		url : "${pageContext.request.contextPath}/baiduMapController/initDataForAll",
		type : "GET",
		async : false,
		dataType : "json",
		success : function(data) {
		    $.each(data, function(index, ele) {
					var point = new BMap.Point(ele.longitude, ele.latitude);
					addMarker(point,ele);
			  });
		}
	});
	
	//地图右键单击事件，左键为click
	map.addEventListener("rightclick", function (e) {
	    lng = e.point.lng;
	    lat = e.point.lat;
	});
	function addRightClickHandler(obj,marker){
		marker.addEventListener("rightclick",function(e){
			  this.obj = obj;
			  lng = e.point.lng;
			  lat = e.point.lat;
			  
			  //alert(this.obj)
		});
	}
	
	function addClickHandler(obj,marker){
		marker.addEventListener("click",function(e){
			var typeName = "场馆";
			if(obj.actType == "11"){
				typeName = "活动";
			}
			var sContent =
				"<div><img style='float:right;margin:4px;vertical-align:middle;' id='imgDemo' src='"+obj.url+"' width='139' height='104' title='海报'/>" +
				"<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em;vertical-align:middle;'>场馆/活动详情信息展示...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/>" +
				"类型："+typeName+"<br/>名称："+obj.title+"<br/>地址："+obj.address+"<br/>坐标："+obj.longitude+","+obj.latitude+"</p>" + 
			    "</div>";
				
			  var infoWindow = new BMap.InfoWindow(sContent);  
			  this.openInfoWindow(infoWindow);
			   //图片加载完毕重绘infowindow
			   document.getElementById('imgDemo').onload = function (){
				   infoWindow.redraw();   //防止在网速较慢，图片未加载时，生成的信息框高度比图片的总高度小，导致图片部分被隐藏
			   };
			  //alert(this.obj)
		});
	}
		// 百度地图API功能
		function G(id) {
			return document.getElementById(id);
		}

		var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : map
		});

		ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
		var str = "";
			var _value = e.fromitem.value;
			var value = "";
			if (e.fromitem.index > -1) {
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			
			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			G("searchResultPanel").innerHTML = str;
		});

		var myValue;
		ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
		var _value = e.item.value;
			myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
			
			setPlace();
		});

		function setPlace(){
			//map.clearOverlays();    //清除地图上所有覆盖物
			function myFun(){
				var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
				map.centerAndZoom(pp, 18);
				map.addOverlay(new BMap.Marker(pp));    //添加标注
			}
			var local = new BMap.LocalSearch(map, { //智能搜索
			  onSearchComplete: myFun
			});
			local.search(myValue);
		}
	/**
	 * 
	 * @Title:addMap
	 * @Description: 初始化活动信息
	 * @param @param  url 链接
	 * @param @param  acttype 类型
	 * @param @param  title  标题
	 * @return void    返回类型
	 */
	function addMap(url,acttype,title){
		$.ajax({
			url :url,
			data : {},
			type : "GET",
			async : false,
			dataType : "json",
			success : function(data) {
				   var options = "<option value='0'>请选择标题</option>";
				   $.each(data, function(index, ele) {
					  options += "<option data-title='"+ele.title+"' data-address='"+ele.address+"' data-url='"+ele.url+"' value='"+ele.actId+"'>"+ele.title+"</option>";
				   });
				   var textHtml = '';
				   textHtml += '<select class="multiselect" name="actid">'+options+'</select>';
				   textHtml += '</br>';
				   textHtml += '</br>';
				   textHtml += '<input type="text" class="form-control" name="longitude"  value="'+lng+'" placeholder="请输入经度" />';
				   textHtml += '</br>';
				   textHtml += '<input type="text" class="form-control" name="latitude"  value="'+lat+'" placeholder="请输入纬度" />';
				   bootbox.confirm({ 
						  size: "small",
						  title: title,
						  message:textHtml, 
						  buttons: {
		  	      	  	        cancel: {
		  	      	  	            label: '<i class="fa fa-times"></i> 取消'
		  	      	  	        },
		  	      	  	        confirm: {
		  	      	  	            label: '<i class="fa fa-check"></i> 提交'
		  	      	  	        }
		  	      	  	  },
						  callback: function(result){
							  if(result){
								 var $sel = $(".multiselect :selected");
								 var address = $sel.data("address");
								 var url = $sel.data("url");
								 var title = $sel.data("title");
								 
								 var actid = $("select[name='actid']").val();
								 var latitude =  $("input[name='latitude']").val();
								 var longitude =  $("input[name='longitude']").val();
								 var params = {actId : actid,actType:acttype,latitude:latitude,longitude:longitude,address:address,url:url,title:title};
									$.ajax({
										url : "${pageContext.request.contextPath}/baiduMapController/addMap",
										data : params,
										type : "POST",
										async : false,
										dataType : "json",
										success : function(data) {
											 var point = new BMap.Point(lng,lat);
											 addMarker(point,params);
										},
										error : function(data) {
											bootbox.alert({ 
												  size: "small",
												  title: "错误",
												  message: "请求超时，请重试！", 
												  callback: function(){return; }
											});
											return;
										}
							  		});
								 
							  } else {
								   lng = "";
								   lat = "";
								   return ;
							  }
						  }
				  });
				   
				  $(".multiselect").multiselect();
			},
			error : function(data) {
				bootbox.alert({ 
					  size: "small",
					  title: "错误",
					  message: "请求超时，请重试！", 
					  callback: function(){return; }
				});
				return;
			}
	   });	
	}
</script>
